package cn.element.netty.experiment;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HelloServer {

    public static void main(String[] args) {
        // 1.服务器端的启动器,负责组装Netty组件,启动服务器
        new ServerBootstrap()
                .group(new NioEventLoopGroup())  // 2.BossEventLoop WorkerEventLoop(selector, thread)
                .channel(NioServerSocketChannel.class)  // 3.选择服务器的ServerSocketChannel实现
                .childHandler(new ChannelInitializer<NioSocketChannel>() {  // 4.Boss负责处理连接worker(child) 负责处理读写,决定了worker(child)能执行哪些操作
                    // 5.channel代表和客户端进行数据读写的通道Initializer初始化,负责添加别的handler
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // 6.添加具体的handler
                        ch.pipeline().addLast(new StringDecoder());  // 将ByteBuffer转换为字符串
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {  // 自定义handler
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                log.info("{}", msg);
                            }
                        });
                    }
                })
                .bind(8080);  // 7.绑定监听端口
    }

}
